package com.netease.nim.chatroom.demo.meeting.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nim.chatroom.demo.DemoCache;
import com.netease.nim.chatroom.demo.R;
import com.netease.nim.chatroom.demo.base.ui.TFragment;
import com.netease.nim.chatroom.demo.base.util.NetworkUtil;
import com.netease.nim.chatroom.demo.meeting.activity.ChatRoomActivity;
import com.netease.nim.chatroom.demo.meeting.helper.ChatRoomMemberCache;
import com.netease.nim.chatroom.demo.meeting.helper.MsgHelper;
import com.netease.nim.chatroom.demo.meeting.helper.VideoListener;
import com.netease.nim.chatroom.demo.meeting.module.MeetingOptCommand;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;

import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hzxuwen on 2016/4/21.
 */
public class ApplyForSpeechFragment extends TFragment implements VideoListener {
    @Bind(R.id.speech_text)
    TextView speechText;
    @Bind(R.id.hands_up_btn)
    Button handsUpBtn;
    @Bind(R.id.give_up_btn)
    Button giveUpBtn;
    @Bind(R.id.applying_layout)
    LinearLayout applyingLayout;
    @Bind(R.id.speaking_layout)
    TextView speakingLayout;
    private View rootView;

    // data
    private String creator;
    private String roomId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.apply_for_speech_fragment, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        creator = ((ChatRoomActivity) getActivity()).getRoomInfo().getCreator();
        roomId = ((ChatRoomActivity) getActivity()).getRoomInfo().getRoomId();
        registerObservers(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        registerObservers(false);
    }

    private void registerObservers(boolean register) {
        ChatRoomMemberCache.getInstance().registerMeetingControlObserver(meetingControlObserver, register);
        ChatRoomMemberCache.getInstance().registerRoomMemberChangedObserver(roomMemberChangedObserver, register);
    }

    ChatRoomMemberCache.MeetingControlObserver meetingControlObserver = new ChatRoomMemberCache.MeetingControlObserver() {
        @Override
        public void onAccept(String roomId) {

        }

        @Override
        public void onReject(String roomID) {
            if (checkRoom(roomID)) {
                return;
            }
            Toast.makeText(DemoCache.getContext(), R.string.speak_reject, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPermissionResponse(String roomId, List<String> accounts) {

        }

        @Override
        public void onSendMyPermission(String roomID, String toAccount) {

        }

        @Override
        public void onSaveMemberPermission(String roomId, List<String> accounts) {

        }

        @Override
        public void onHandsUp(String roomId, String account) {

        }

        @Override
        public void onHandsDown(String roomID, String account) {

        }

        @Override
        public void onStatusNotify(String roomID, List<String> accounts) {
            if (checkRoom(roomID)) {
                return;
            }
            checkPermission();
        }
    };

    ChatRoomMemberCache.RoomMemberChangedObserver roomMemberChangedObserver = new ChatRoomMemberCache.RoomMemberChangedObserver() {
        @Override
        public void onRoomMemberIn(ChatRoomMember member) {
            if (member.getAccount().equals(creator)) {
                // 主持人重新进来,观众要取消自己的举手状态
                ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, false);
                checkPermission();
            }
        }

        @Override
        public void onRoomMemberExit(ChatRoomMember member) {

        }
    };

    private boolean checkRoom(String roomID) {
        return TextUtils.isEmpty(roomId) || !roomId.equals(roomID);
    }

    @OnClick({R.id.hands_up_btn, R.id.give_up_btn})
    public void onClick(View view) {
        if (!NetworkUtil.isNetAvailable(getActivity())) {
            Toast.makeText(getActivity(), R.string.network_is_not_available, Toast.LENGTH_SHORT).show();
            return;
        }
        switch (view.getId()) {
            case R.id.hands_up_btn:
                MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_REQUEST.getValue(),
                        creator, null);
                ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, true);
                break;
            case R.id.give_up_btn:
                MsgHelper.getInstance().sendP2PCustomNotification(roomId, MeetingOptCommand.SPEAK_REQUEST_CANCEL.getValue(),
                        creator, null);
                ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, false);
                break;
        }
        switchLayout();
    }

    // 检查自己是否有发言权限
    public void checkPermission() {
        if (ChatRoomMemberCache.getInstance().hasPermission(roomId, DemoCache.getAccount())) {
            // 有权限，正在发言
            speakingLayout.setVisibility(View.VISIBLE);
            handsUpBtn.setVisibility(View.GONE);
            applyingLayout.setVisibility(View.GONE);
            ChatRoomMemberCache.getInstance().saveMyHandsUpDown(roomId, false);
        } else {
            // 没有权限，判断是否举手申请中
            switchLayout();
            speakingLayout.setVisibility(View.GONE);
        }
        setSpeechPeopleText(ChatRoomMemberCache.getInstance().getPermissionMemsEx(roomId));
    }

    // 举手布局/取消举手布局切换
    private void switchLayout() {
        if (ChatRoomMemberCache.getInstance().isMyHandsUp(roomId)) {
            handsUpBtn.setVisibility(View.GONE);
            applyingLayout.setVisibility(View.VISIBLE);
        } else {
            handsUpBtn.setVisibility(View.VISIBLE);
            applyingLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    // 设置正在发言人
    private void setSpeechPeopleText(List<ChatRoomMember> members) {
        StringBuilder sb = new StringBuilder();
        if (members != null && !members.isEmpty()) {
            for (ChatRoomMember a : members) {
                sb.append(a.getNick()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
        }

        speechText.setText(String.format(getString(R.string.speeching), sb));
    }

    @Override
    public void onVideoOn(String account) {

    }

    @Override
    public void onVideoOff(String account) {

    }

    @Override
    public void onTabChange(boolean notify) {

    }

    @Override
    public void onKickOutSuccess(String account) {

    }

    @Override
    public void onUserLeave(String account) {
        checkPermission();
    }

    @Override
    public void onReportSpeaker(Map<String, Integer> map) {

    }

    @Override
    public void onAcceptConfirm() {

    }
}
